#coding:utf-8
import zipfile
import os

class ZipFile:

    def zip_file(filePath, savePath,zipfilename, note=''):
        '''
        将文件夹下的文件保存到zip文件中。
        params:
            filePath: 待备份文件
            savePath: 备份路径
            zipfilename:备份文件名
            note: 备份文件说明
        :return:
        '''
        try:
            fileList = []
            if not os.path.exists(savePath):
                os.mkdir(savePath)
                print('mkdir successful')
            target = savePath + os.sep + zipfilename + '.zip'
            newZip = zipfile.ZipFile(target, 'w')
            for dirpath, dirnames, filenames in os.walk(filePath):
                for filename in filenames:
                    fileList.append(os.path.join(dirpath, filename))
            for tar in fileList:
                newZip.write(tar, tar[len(filePath):])  # tar为写入的文件，tar[len(filePath)]为保存的文件名
            newZip.close()
            return True
        except Exception as e:
            return False


    def unzip_file(zfile_path, unzip_dir):
        '''
          function:解压
          params:
              zfile_path:压缩文件路径
              unzip_dir:解压缩路径
          description:
        '''
        try:
            with zipfile.ZipFile(zfile_path) as zfile:
                zfile.extractall(path=unzip_dir)
                return True
        except Exception as e:
            return False



if __name__ == '__main__':
   # ZipFile.unzip_file(r'../tools/POSBase.zip',r'../tools/tmp')
    ZipFile.zip_file(r'..\webapp',r'..\tools2','webappzip')